package com.yeshine.opendata.core;

import com.yeshine.opendata.utils.JsonResult;
import com.yeshine.opendata.utils.Result;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * Created by taohj on 2014/4/1.
 */

@RequestMapping(produces = "application/json; charset=utf-8")
public abstract class ControllerBase {
    Logger logger = Logger.getLogger(getClass());

    public  static  HttpServletRequest getRequest() {
        ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return t.getRequest();
    }




    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public void setRequestAttr(String name, Object obj) {
        getRequest().setAttribute(name, obj);
    }


    public Object getRequestAttr(String name) {
        return  getRequest().getAttribute(name);
    }

    public void setSessionAttr(String name, Object obj) {
        getSession().setAttribute(name, obj);
    }

    public Object getSessionAttr(String name) {
        return  getSession().getAttribute(name);
    }





    public String getBasePath(){
        HttpServletRequest request=getRequest();
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path;
        return  basePath;
    }

    public JsonResult getSuccessJsonResult(String message){
        JsonResult result=new JsonResult();
        result.setSuccess(true);
        result.setMessage(message);
        return result;
    }


    public JsonResult getFailureJsonResult(String message){
        JsonResult result=new JsonResult();
        result.setSuccess(false);
        result.setMessage(message);
        return result;
    }


    public  String getReturnString(Result result,String success,String fail){

        if (result.isSuccess()){
            return success;
        }else{
            return fail;
        }
    }


    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public String handleException(final Throwable e,
                                final HttpServletRequest request, final HttpServletResponse response)
            throws IOException {
        Result result = new Result(false,e.getMessage());
        e.printStackTrace();
        return result.toString();
    }





}
